/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.factory.comport.uart;

import com.factory.comport.helper.CircularArrayList;
import com.factory.comport.helper.ModbusCRC;
import com.factory.comport.helper.constants.ModbusConstants;
import java.util.logging.Level;
import java.util.logging.Logger;
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;

/**
 *
 * @author MinhLuan
 */
public class SerialPortReader implements SerialPortEventListener {

    private SerialPort m_pSerialPort;
    private CircularArrayList<Byte> m_pReceivedData = new CircularArrayList<Byte>(ModbusConstants.MOBUS_REPLY_MESSAGE_LENGTH);

    public SerialPortReader(SerialPort serialPort) {
        this.m_pSerialPort = serialPort;
    }

    @Override
    public void serialEvent(SerialPortEvent event) {
        if (event.isRXCHAR()) {//If data is available
            if (event.getEventValue() == ModbusConstants.MOBUS_REPLY_MESSAGE_LENGTH) {
                try {
                    byte buffer[] = m_pSerialPort.readBytes();

                    //Calculate the CRC
                    int crc = ModbusCRC.doCRC16(buffer, 0, ModbusConstants.MOBUS_REPLY_MESSAGE_LENGTH - 2);
                    if (((byte) (crc & 0x000000ff)) == buffer[ModbusConstants.MOBUS_REPLY_MESSAGE_LENGTH - 2]
                            && ((byte) ((crc & 0x0000ff00) >> 8)) == buffer[ModbusConstants.MOBUS_REPLY_MESSAGE_LENGTH - 1]) {  //Right CRC
                        System.out.println("Right CRC");
                    }

                } catch (SerialPortException ex) {
                    Logger.getLogger(SerialPortReader.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}
